package com.study.service.impl;

import com.study.model.MsgCode;
import com.study.service.MsgCodeService;
import com.study.utils.MsgCodeUtils;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeoutException;

/**
 * @desc:
 * @author: panxiyi
 * @date: 2023/5/3 11:52 下午
 */

@Service
public class MsgCodeServiceImpl implements MsgCodeService {

    @Autowired
    private MsgCodeUtils msgCodeUtils;

//    @Override
//    @CachePut(value = "msgCode", key = "#tele") // 默认的缓存是Simple
//    public String genCode(String tele) {
//        return msgCodeUtils.generator(tele);
//    }
//
//    @Override
//    public boolean checkCode(MsgCode msgCode) {
//
//        String serverMsgCode = msgCodeUtils.getMsgCode(msgCode.getTele());
//
//        return msgCode.getCode().equals(serverMsgCode);
//    }


    // 以下是springboot中使用xmemcached

    @Autowired
    private MemcachedClient memcachedClient;

    @Override
    public String genCode(String tele) {
        String code = msgCodeUtils.generator(tele);
        try {
            memcachedClient.set(tele, 10, code);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return code;
    }

    @Override
    public boolean checkCode(MsgCode msgCode) {
        String code = "";
        try {
            Object codeObj = memcachedClient.get(msgCode.getTele());
            if (codeObj != null) {
                code = codeObj.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return msgCode.getCode().equals(code);
    }
}
